import React, { useState, useEffect } from 'react';
import { 
  Form, 
  Input, 
  Button, 
  Card, 
  Switch, 
  Select, 
  InputNumber, 
  Divider, 
  message, 
  Typography,
  Row,
  Col,
  Space,
  Tooltip,
  Tag,
  List,
  Alert
} from 'antd';
import { 
  SaveOutlined, 
  ReloadOutlined, 
  EyeInvisibleOutlined, 
  NumberOutlined,
  PictureOutlined,
  QuestionCircleOutlined,
  PlusOutlined,
  CloseCircleOutlined,
  SafetyCertificateOutlined
} from '@ant-design/icons';
import api from '../../../services/api';

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;
const { TextArea } = Input;

const SensitiveContentSettings = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [numberPattern, setNumberPattern] = useState('');
  const [numberPatterns, setNumberPatterns] = useState([]);
  const [sensitiveKeyword, setSensitiveKeyword] = useState('');
  const [sensitiveKeywords, setSensitiveKeywords] = useState([]);

  // 在组件加载时获取当前设置
  useEffect(() => {
    fetchSettings();
  }, []);

  // 获取敏感内容设置
  const fetchSettings = async () => {
    setLoading(true);
    try {
      // 调用真实API获取设置
      const response = await api.get('/settings/filter/sensitive');
      
      // 设置表单值
      if (response.data) {
        form.setFieldsValue({
          enableNumberMasking: response.data.enableNumberMasking,
          numberMaskingPattern: response.data.numberMaskingPattern,
          enableLongNumberDetection: response.data.enableLongNumberDetection,
          longNumberThreshold: response.data.longNumberThreshold,
          detectCreditCards: response.data.detectCreditCards,
          detectPhoneNumbers: response.data.detectPhoneNumbers,
          enableImageFiltering: response.data.enableImageFiltering,
          imageFilteringLevel: response.data.imageFilteringLevel,
          storeOriginalContent: response.data.storeOriginalContent,
          notifyAdminOnDetection: response.data.notifyAdminOnDetection
        });
        
        // 设置敏感数字模式和敏感关键词
        if (response.data.numberPatterns) {
          setNumberPatterns(response.data.numberPatterns);
        }
        
        if (response.data.sensitiveKeywords) {
          setSensitiveKeywords(response.data.sensitiveKeywords);
        }
      }
    } catch (error) {
      console.error('获取敏感内容设置失败:', error);
      message.error('获取敏感内容设置失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 保存敏感内容设置
  const handleSave = async (values) => {
    setSaving(true);
    try {
      // 添加敏感数字模式和敏感关键词到表单值
      const formData = {
        ...values,
        numberPatterns,
        sensitiveKeywords
      };
      
      // 将设置保存到后端
      await api.post('/settings/filter/sensitive', formData);
      message.success('敏感内容设置已保存');
    } catch (error) {
      console.error('保存敏感内容设置失败:', error);
      message.error('保存敏感内容设置失败，请重试');
    } finally {
      setSaving(false);
    }
  };

  // 添加敏感数字模式
  const addNumberPattern = () => {
    if (!numberPattern || numberPattern.trim() === '') {
      message.error('请输入有效的数字模式');
      return;
    }
    
    if (numberPatterns.includes(numberPattern)) {
      message.warning('该数字模式已存在');
      return;
    }
    
    setNumberPatterns([...numberPatterns, numberPattern]);
    setNumberPattern('');
  };

  // 删除敏感数字模式
  const removeNumberPattern = (pattern) => {
    setNumberPatterns(numberPatterns.filter(p => p !== pattern));
  };

  // 添加敏感关键词
  const addSensitiveKeyword = () => {
    if (!sensitiveKeyword || sensitiveKeyword.trim() === '') {
      message.error('请输入有效的关键词');
      return;
    }
    
    if (sensitiveKeywords.includes(sensitiveKeyword)) {
      message.warning('该关键词已存在');
      return;
    }
    
    setSensitiveKeywords([...sensitiveKeywords, sensitiveKeyword]);
    setSensitiveKeyword('');
  };

  // 删除敏感关键词
  const removeSensitiveKeyword = (keyword) => {
    setSensitiveKeywords(sensitiveKeywords.filter(k => k !== keyword));
  };

  return (
    <div className="sensitive-content-settings-container">
      <Card 
        title={
          <Space>
            <SafetyCertificateOutlined />
            <span>敏感内容过滤设置</span>
          </Space>
        }
        bordered={false}
        loading={loading}
      >
        <Alert
          message="敏感内容过滤说明"
          description="设置系统如何识别和处理敏感内容，保护客户隐私并确保销售人员不会看到敏感信息。"
          type="info"
          showIcon
          style={{ marginBottom: 24 }}
        />
        
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Divider orientation="left">号码掩码设置</Divider>
          
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="enableNumberMasking"
                label="启用号码掩码"
                valuePropName="checked"
                tooltip="开启后，销售人员将无法看到客户的完整电话号码"
              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="numberMaskingPattern"
                label="号码掩码模式"
                tooltip="使用#显示原始数字，*显示掩码。例如：###****##会显示前3位和后2位，中间用*替代"
                rules={[{ required: true, message: '请输入号码掩码模式' }]}
              >
                <Input 
                  placeholder="例如：###****##" 
                  prefix={<EyeInvisibleOutlined />}
                />
              </Form.Item>
            </Col>
          </Row>

          <Divider orientation="left">敏感数字检测</Divider>
          
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="enableLongNumberDetection"
                label="启用长数字串检测"
                valuePropName="checked"
                tooltip="自动检测并掩盖消息中的长数字串，如信用卡号、身份证号等"
              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="longNumberThreshold"
                label="长数字串阈值"
                tooltip="大于等于此长度的连续数字将被识别为敏感信息"
                rules={[{ required: true, message: '请输入长数字串阈值' }]}
              >
                <InputNumber 
                  min={4} 
                  max={20} 
                  style={{ width: '100%' }}
                  prefix={<NumberOutlined />}
                />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="detectCreditCards"
                label="检测信用卡号"
                valuePropName="checked"
                tooltip="使用Luhn算法自动识别和掩盖消息中的信用卡号"
              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="detectPhoneNumbers"
                label="检测电话号码"
                valuePropName="checked"
                tooltip="自动识别和掩盖消息中的电话号码"
              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" />
              </Form.Item>
            </Col>
          </Row>

          <div style={{ marginBottom: 16 }}>
            <Text strong>敏感数字模式</Text>
            <Tooltip title="使用正则表达式定义敏感数字模式">
              <QuestionCircleOutlined style={{ marginLeft: 8 }} />
            </Tooltip>
            <div style={{ display: 'flex', marginTop: 8, marginBottom: 8 }}>
              <Input
                placeholder="输入正则表达式模式"
                value={numberPattern}
                onChange={(e) => setNumberPattern(e.target.value)}
                style={{ flex: 1, marginRight: 8 }}
              />
              <Button type="primary" onClick={addNumberPattern}>
                添加
              </Button>
            </div>
            <div>
              {numberPatterns.map((pattern, index) => (
                <Tag 
                  key={index} 
                  closable 
                  onClose={() => removeNumberPattern(pattern)}
                  style={{ marginBottom: 8 }}
                >
                  {pattern}
                </Tag>
              ))}
            </div>
          </div>

          <div style={{ marginBottom: 16 }}>
            <Text strong>敏感关键词</Text>
            <Tooltip title="包含这些关键词的消息会被标记为敏感">
              <QuestionCircleOutlined style={{ marginLeft: 8 }} />
            </Tooltip>
            <div style={{ display: 'flex', marginTop: 8, marginBottom: 8 }}>
              <Input
                placeholder="输入敏感关键词"
                value={sensitiveKeyword}
                onChange={(e) => setSensitiveKeyword(e.target.value)}
                style={{ flex: 1, marginRight: 8 }}
              />
              <Button type="primary" onClick={addSensitiveKeyword}>
                添加
              </Button>
            </div>
            <div>
              {sensitiveKeywords.map((keyword, index) => (
                <Tag 
                  key={index} 
                  closable 
                  color="red"
                  onClose={() => removeSensitiveKeyword(keyword)}
                  style={{ marginBottom: 8 }}
                >
                  {keyword}
                </Tag>
              ))}
            </div>
          </div>

          <Divider orientation="left">图片内容过滤</Divider>
          
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="enableImageFiltering"
                label="启用图片过滤"
                valuePropName="checked"
                tooltip="控制销售人员查看客户发送的图片"
              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="imageFilteringLevel"
                label="图片过滤级别"
                tooltip="设置图片过滤的严格程度"
                rules={[{ required: true, message: '请选择图片过滤级别' }]}
              >
                <Select placeholder="选择过滤级别">
                  <Option value="low">低 (仅过滤明显敏感图片)</Option>
                  <Option value="medium">中 (过滤大部分图片，管理员可查看)</Option>
                  <Option value="high">高 (过滤所有图片，需管理员审核)</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Divider orientation="left">其他设置</Divider>
          
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="storeOriginalContent"
                label="保存原始内容"
                valuePropName="checked"
                tooltip="保存敏感内容的原始版本，以便管理员查看"
              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="notifyAdminOnDetection"
                label="敏感内容提醒管理员"
                valuePropName="checked"
                tooltip="当检测到敏感内容时，通知管理员"
              >
                <Switch checkedChildren="开启" unCheckedChildren="关闭" />
              </Form.Item>
            </Col>
          </Row>

          <Divider />

          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                icon={<SaveOutlined />}
                loading={saving}
              >
                保存设置
              </Button>
              <Button
                icon={<ReloadOutlined />}
                onClick={fetchSettings}
                disabled={loading}
              >
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default SensitiveContentSettings; 